using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Claims;

namespace UniversalAdminSystem.Api.Attributes;

/// <summary>
/// 角色验证特性
/// 用于标记需要特定角色的API接口
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequireRoleAttribute : Attribute, IAsyncAuthorizationFilter
{
    private readonly string _roleName;

    public RequireRoleAttribute(string roleName)
    {
        _roleName = roleName;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        try
        {
            // 获取用户角色
            var userRole = context.HttpContext.User.FindFirst(ClaimTypes.Role)?.Value;
            if (string.IsNullOrEmpty(userRole))
            {
                context.Result = new UnauthorizedResult();
                return;
            }

            // 检查用户角色是否匹配
            if (userRole != _roleName)
            {
                context.Result = new ForbidResult();
                return;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"角色验证错误: {ex.Message}");
            context.Result = new StatusCodeResult(500);
        }
    }
}